package alarm.ruiqi.com.alarm_pro.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.widget.TimePicker;

import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.util.LogUtils;

import java.util.Calendar;
import java.util.HashSet;
import java.util.List;

import alarm.ruiqi.com.alarm_pro.domain.AlarmEntity;
import alarm.ruiqi.com.alarm_pro.recevier.AlarmReceiver;
import alarm.ruiqi.com.alarm_pro.utils.Constant;

/**
 * Created by 徐宇健 on 2015/7/28 0028.
 * 闹钟业务逻辑
 */
public class AlarmServiceImpl {
    public  static  final String WORK_DAY = "工作日"; //1,2,3,4,5
    public  static  final String EVERY_DAY = "每天";
    public  static  final String ONLY_ONCE = "仅一次";



    public enum Repeat {
        七(1) ,
        一(2),
        二(3),
        三(4),
        四(5),
        五(6),
        六(7);
        // 定义私有变量
        private int nCode ;
        Repeat(int s){ this.nCode = s;}

    }

    private Context context;
    public AlarmServiceImpl(Context ctx){
        this.context = ctx;
    }

    /**
     * 保存闹钟前的检查
     * @param entity
     * @param flag
     * @param picker
     * @return
     */
    public AlarmEntity checkAlarmBeforeSave(AlarmEntity entity, boolean flag, TimePicker picker){
        entity.setEnable(flag);
        Calendar calendar = calculateAlarmTime(picker.getCurrentHour(), picker.getCurrentMinute(),entity.getInterValDate(false));
        entity.setAlarmTime(calendar.getTimeInMillis());
        entity.setDescription(entity.getAlarminfo());
        return entity;
    }

    private Calendar calculateAlarmTime(int hourOfDay, int minute,Integer interval) {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, interval);
        cal.set(Calendar.HOUR_OF_DAY, hourOfDay);
        cal.set(Calendar.MINUTE, minute);
        return cal;
    }

    public void createAlarm(Context context, AlarmEntity entity, boolean flag) {
        //是否需要cancel闹钟
            //保存闹钟
            LogUtils.i( flag +" >>> 闹钟 Alarm = " + entity);
            Intent intent = new Intent(context.getApplicationContext(), AlarmReceiver.class);
            intent.setAction(String.format("android_intent_action_%d_%s_alarm",entity.getId(),entity.getAlarm_Format()));
            intent.putExtra(Constant.GENERAL_SAVE_KEY, entity);
            if(flag){
                //创建闹钟服务
                AlarmManager alarmMgr = (AlarmManager)context. getSystemService(Context.ALARM_SERVICE);
                PendingIntent pendIntent = PendingIntent.getBroadcast(context.getApplicationContext(),  entity.getId() , intent, 0);
                alarmMgr.set(AlarmManager.RTC_WAKEUP, entity.getAlarmTime(), pendIntent);
                LogUtils.i("创建成功; pendIntent ="+pendIntent.toString());
            }else {
                //关闭闹钟
                AlarmManager alarmMgr = (AlarmManager)context. getSystemService(Context.ALARM_SERVICE);
                PendingIntent pendIntent = PendingIntent.getBroadcast(context.getApplicationContext(), entity.getId(), intent, 0);
                alarmMgr.cancel(pendIntent);
                LogUtils.i("取消成功; pendIntent ="+pendIntent.toString());
            }
    }
    //================== 重复周期======================

    /**
     * 是否是工作日 12345
     * @param hashSetRepeats
     * @return
     */
    public boolean isWorkday(HashSet<Integer> hashSetRepeats){
        if (hashSetRepeats.size()!=5) return false;
        for (int i = 2 ; i<7 ; i++){
           if( ! hashSetRepeats.contains(Repeat.values()[i].nCode - 1))
               return false;
        }
        return  true;
    }

    /**
     * 仅一次
     * @param hashSetRepeats
     * @return
     */
    public boolean isOnlyOnce(HashSet<Integer> hashSetRepeats) {
        return hashSetRepeats.size()==0;
    }

    /**
     * 每天
     * @param hashSetRepeats
     * @return
     */
    public boolean isEveryDay(HashSet<Integer> hashSetRepeats) {
        return hashSetRepeats.size() == 7;
    }

    /**
     * 获取重复周期的显示字符串
     * @param hashSetRepeats
     * @return
     */
    public String getRepeat_s(HashSet<Integer> hashSetRepeats) {
        StringBuilder sb = new StringBuilder();
        for (int i = 1 ; i<=6 ; i++){
            if (hashSetRepeats.contains(i+1)){
                sb.append(Repeat.values()[i]);
                sb.append(" ");
            }
        }
        if (hashSetRepeats.contains(1)){
            sb.append(Repeat.values()[0]);
        }

        return sb.toString();
    }

    /**
     * 检查闹钟,有重复周期
     * @param alarmEntity
     * @param timeNow
     * @return
     */
    public  AlarmEntity checkNextAlarm(AlarmEntity alarmEntity, long timeNow){
        HashSet<Integer> repeat = alarmEntity.getHashSetRepeats();
        //检查enable状态并设置alarmTime enable 为true
        Calendar calendar = alarmEntity.getCalendar();

        //过期
        if (alarmEntity.isEnable()){
            if (alarmEntity.getAlarmTime() < timeNow ){
                //闹钟已经结束
                if (repeat.size() == 0)
                    //仅一次
                    alarmEntity.setEnable(false);
                else{
                    //有重复周期
                    alarmEntity.setEnable(true);
                    int interval = alarmEntity.getMinInterval(alarmEntity.getHashSetRepeats(), Calendar.getInstance().get(Calendar.DAY_OF_WEEK),alarmEntity.getAlarmTime()<timeNow);
                    alarmEntity.setInterValDate(interval);
                    if (interval == 0){
                        if (timeNow> calendar.getTimeInMillis())
                            interval = 1;
                    }


                    calendar.add(Calendar.DATE, interval);//如果间隔为0 需要判定
                    alarmEntity.setCalendar(calendar);
                    alarmEntity.setAlarmTime(calendar.getTimeInMillis());
                }

            }
        }
        alarmEntity.setDescription(alarmEntity.getAlarminfo());
        return alarmEntity;
    }


    /***
     * 检查下个闹钟,针对list
     * @param alarmEntities
     * @param timeNow
     * @return
     */
    public List<AlarmEntity> checkNextAlarms(List<AlarmEntity> alarmEntities, long timeNow){
        if (alarmEntities == null) return  null;
        for (AlarmEntity entity:alarmEntities){
            entity  =  checkNextAlarm(entity, timeNow);
        }
        return alarmEntities;
    }

    /**
     * 保存闹钟到数据库
     * @param entity
     */
    public void saveAlarm(AlarmEntity entity) throws DbException {
            MobileApplication.getInstance().getDefaultDbutils().update(entity);
    }


    /**
     * 重新保存数据
     * @param dbUtils
     * @param entity
     * @param isNew
     * @return
     */
    public boolean reSaveAll(DbUtils dbUtils,AlarmEntity entity,boolean isNew) {
        LogUtils.e("创建闹钟失败,正在解决!");
        try {

            List<AlarmEntity> es =  dbUtils.findAll(AlarmEntity.class);
            dbUtils.dropTable(AlarmEntity.class);
            dbUtils.saveAll(es);
            if (isNew){
                dbUtils.saveBindingId(entity); //保存数据库
            }else {
                dbUtils.update(entity);
            }
            LogUtils.e("解决成功");
        } catch (DbException e1) {
            e1.printStackTrace();
            LogUtils.e("创建闹钟失败,重新尝试!");
            return false;
        }
        return  true ;
    }

    /**
     * 设置运行
     * @return
     * @param data
     * @param isChecked
     */
    public AlarmEntity changeEnable(AlarmEntity data, boolean isChecked) {
        data.setEnable(isChecked);
        Calendar now = Calendar.getInstance();
        if (isChecked && data.getAlarmTime() < now.getTimeInMillis() && data.getHashSetRepeats().size() == 0) {
            Calendar c = data.getCalendar();
            if (c.get(Calendar.HOUR_OF_DAY) < now.get(Calendar.HOUR_OF_DAY) || (c.get(Calendar.HOUR_OF_DAY) == now.get(Calendar.HOUR_OF_DAY) && c.get(Calendar.MINUTE) < now.get(Calendar.MINUTE))) {
                now.add(Calendar.DATE, 1);
            }
            now.set(Calendar.HOUR_OF_DAY, c.get(Calendar.HOUR_OF_DAY));
            now.set(Calendar.MINUTE, c.get(Calendar.MINUTE));
            data.setAlarmTime(now.getTimeInMillis());
            data.setDescription(data.getAlarminfo());
        }
        LogUtils.i("alarm time =" + data.getAlarm_Format());
        return data;
    }



    /**
     * 取消闹钟并删除
     */
    public void cancelAndeleteAlarms(DbUtils dbUtils, List<AlarmEntity> ens) throws DbException {
        for (AlarmEntity e:ens){
            if (e.isEnable())
                createAlarm(MobileApplication.getInstance(),e,false);
            dbUtils.delete(e);

        }
    }


}
